import { AbstractModel } from '@/model/model'
import { imageMap } from '@/service/image'
import Tank, { type Direct } from './tank'
import bulletCanvas from '@/canvas/bullet'

class Bullet extends AbstractModel {
    public direct: Direct

    private timer: any = null

    /**
     * 构造函数
     * @param ctx Canvas context
     * @param x  子弹位置-x
     * @param y  子弹位置-y
     * @param direct 方向
     * @param width  宽度
     * @param height  高度
     */
    public constructor(x: number, y: number, direct: Direct, width = 8, height = 8) {
        super(bulletCanvas.ctx, { x, y })
        this.direct = direct
        this.width = width
        this.height = height
    }

    /**
     * 静态方法：根据坦克的位置创建子弹
     * @param tank 坦克对象
     * @param width 子弹宽度
     * @param height 子弹高度
     * @returns
     */
    public static create(tank: Tank, width = 8, height = 8) {
        return new Bullet(tank.x + tank.width / 2 - width / 2, tank.y + tank.height / 2 - height / 2, tank.direct, width, height)
    }

    public render() {
        this.timer = setInterval(() => {
            this.clear()
            this.move()
            this.draw()
        }, 20)
    }

    private clear() {
        this.ctx.clearRect(this.x, this.y, this.width, this.height)
    }

    private move() {
        const step = 8
        switch (this.direct) {
            case 'top':
                this.y -= step
                break
            case 'right':
                this.x += step
                break
            case 'bottom':
                this.y += step
                break
            case 'left':
                this.x -= step
                break
        }
        console.log(this.x, this.y)

        // 子弹飞出画布, 停止定时器
        if (this.x - this.width < -20 || this.y - this.height < -20 || this.x > bulletCanvas.width + 20 || this.y > bulletCanvas.height + 20) {
            clearInterval(this.timer)
        }
    }

    protected getImage(): HTMLImageElement {
        return imageMap.get('bullet')!
    }
}

export default Bullet
